<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/10
 * Time: 14:08
 */

namespace app\controllers;


use yii;
use app\lib\BaseFunction;
use app\models\AdminUser;

class AdminController extends ApiBaseController
{
    /**
     * 后台用户列表
     */
    public function actionUser()
    {
        $model = new AdminUser();
        $list = $model->get_all_user();
        $role = $model->get_admin_role('id,role_name');

        //所有员工
        $model = new \app\models\Staff();
        $staff = $model->get_staff_list();
        $hasRegister = array_column($list, 'staff_id');
        $arr = [];
        foreach ($staff as $v) {
            if ((int)$v['status'] === 0) {
                if (!in_array($v['id'], $hasRegister)) {
                    $arr[] = $v;
                }
            }
        }
        return \json_encode(['staff' => $arr, 'list' => $list, 'role' => $role]);
    }

    public function actionDel()
    {
        $id = yii::$app->request->post('id');
        BaseFunction::check_edit_auth($this->user['role']);
        if (is_numeric($id) && $id > 0) {
            $model = new AdminUser();
            $re = $model->delete(['id' => $id]);
            if ($re) {
                $data = ['code' => 1, 'msg' => '删除成功'];
            } else {
                $data = ['code' => 0, 'msg' => '删除失败,请重试'];
            }
            return \json_encode($data);
        }
    }

    public function actionAdd()
    {
        $data = yii::$app->request->post();
        $data['time'] = time();
        $data['password'] = md5($data['password']);
        $model = new AdminUser();
        $re = $model->one(['name' => $data['name']]);
        if ($re) {
            return \json_encode(['code' => 0, 'msg' => '该账户名称已存在']);
        }
        $re = $model->insert($data);
        if ($re) {
            $data = ['code' => 1, 'msg' => '删除成功'];
        } else {
            $data = ['code' => 0, 'msg' => '删除失败,请重试'];
        }
        return \json_encode($data);

    }
}